import {
  _decorator,
  warn,
  Asset,
  AudioClip,
  Prefab,
  SpriteFrame,
  resources,
} from "cc"

const { ccclass, property } = _decorator

@ccclass
export default class ResManager {
  private static _instance: ResManager = null
  public static get instance() {
    if (!ResManager._instance) ResManager._instance = new ResManager()
    return ResManager._instance
  }

  private _resources = {}


  /**
   * 加载resources文件下相关资源结构文件夹的资源
   * @param url 资源路径
   * @param type 资源类型Prefab,SpriteFrame,JsonAsset,AudioClip
   * @param complete 加载回调函数，通过判断error，是否加载成功
   * @returns 
   */
  public loadRes(url: string, type: typeof Asset, complete: Function) {
    if (this._resources[url]) {
      complete && complete(null, this._resources[url])
      return
    }

    let loadUrl = url
    if (type === SpriteFrame) {
      loadUrl += "/spriteFrame"
    }
    resources.load(loadUrl, type, (error: Error, resource: any) => {
      if (!error) {
        this._resources[url] = resource
      } else {
        console.warn(error)
      }
      complete && complete(error, resource)
    })
  }
  public getRes(url: string, type: typeof Asset = Prefab) {
    let res: any = resources.get(url, type)
    return res
  }


  /**
   * 加载resources文件下相关资源结构文件夹的所有资源
   * @param url 资源路径
   * @param type 资源类型Prefab,SpriteFrame,JsonAsset,AudioClip
   * @param complete 加载回调函数，通过判断error，是否加载成功
   * @returns 
   */
  public loadDirRes(url: string, type: typeof Asset, complete: Function) {
    if (this._resources[url]) {
      complete && complete(null, this._resources[url])
      return
    }
    let loadUrl = url
    resources.loadDir(loadUrl, type, (error: Error, resource: any) => {
      if (!error) {
        this._resources[url] = resource
      } else {
        console.warn(error)
      }
      complete && complete(error, resource)
    })
  }
}
